package com.whm.hrmanagement.service.impl;

import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import cn.hutool.core.date.DateUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whm.common.core.domain.entity.SysUser;
import com.whm.common.enums.EnumUtil;
import com.whm.common.enums.OaStaffAttendanceEnum;
import com.whm.common.utils.DateUtils;
import com.whm.common.utils.html.DatetimeUtil;
import com.whm.hrmanagement.domain.vo.AttendanceMonthVO;
import com.whm.hrmanagement.domain.vo.OaAttendanceVo;
import com.whm.system.domain.dto.UserAttendanceDto;
import com.whm.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import com.whm.hrmanagement.mapper.OaStaffAttendanceMapper;
import com.whm.hrmanagement.domain.OaStaffAttendance;
import com.whm.hrmanagement.service.IOaStaffAttendanceService;

import javax.servlet.http.HttpServletResponse;

/**
 * 员工考勤Service业务层处理
 * 
 * @author whm
 * @date 2024-02-06
 */
@Service
public class OaStaffAttendanceServiceImpl  extends ServiceImpl<OaStaffAttendanceMapper, OaStaffAttendance> implements IOaStaffAttendanceService
{
    @Autowired
    private OaStaffAttendanceMapper oaStaffAttendanceMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    /***
     * 查询员工考勤
     * 
     * @param id 员工考勤主键
     * @return 员工考勤
     */
    @Override
    public OaStaffAttendance selectOaStaffAttendanceById(Long id)
    {
        return oaStaffAttendanceMapper.selectOaStaffAttendanceById(id);
    }

    @Override
    public List<Map<String, Object>> findAll() {
        List<Map<String, Object>> enumList = EnumUtil.getEnumList(OaStaffAttendanceEnum.class);
        for (Map<String, Object> map : enumList) {
            for (OaStaffAttendanceEnum attendanceStatusEnum : OaStaffAttendanceEnum.values()) {
                if (map.get("code") == attendanceStatusEnum.getCode()) {
                    map.put("tagType", attendanceStatusEnum.getTagType());
                }
            }
        }
        return enumList;
    }

    @Override
    public OaStaffAttendance findByStaffIdAndDate(Long id, String date) {

        OaStaffAttendance oaStaffAttendance =oaStaffAttendanceMapper.findByStaffId(id,  date.replace("-", ""));

        if (oaStaffAttendance != null) {
            return oaStaffAttendance;
        }
        return null;


    }

    @Override
    public List<AttendanceMonthVO> export(OaAttendanceVo oaAttendanceVo) {
        String month =oaAttendanceVo.getMonth();
        if (month == null) {
            month = DateUtil.format(new java.util.Date(), "yyyyMM");
        }

        List<AttendanceMonthVO> list = this.oaStaffAttendanceMapper.findAttendanceMonthVO();
        for (AttendanceMonthVO attendanceMonthVO : list) {
            // 设置迟到次数
            attendanceMonthVO.setLateTimes(this.oaStaffAttendanceMapper.countTimes(attendanceMonthVO.getStaffId(),
                    OaStaffAttendanceEnum.LATE.getCode(), month));
            // 设置早退次数
            attendanceMonthVO.setLeaveEarlyTimes(this.oaStaffAttendanceMapper.countTimes(attendanceMonthVO.getStaffId(),
                    OaStaffAttendanceEnum.LEAVE_EARLY.getCode(), month));
            // 设置旷工次数
            attendanceMonthVO.setAbsenteeismTimes(this.oaStaffAttendanceMapper.countTimes(attendanceMonthVO.getStaffId(),
                    OaStaffAttendanceEnum.ABSENTEEISM.getCode(), month));
            // 设置休假天数
            List<Date> leaveDateList = this.oaStaffAttendanceMapper.findLeaveDate(attendanceMonthVO.getStaffId(),
                    OaStaffAttendanceEnum.LEAVE.getCode(), month);
            int count = 0;
            for (Date date : leaveDateList) {
                // 不包括周末
                if (!DateUtil.isWeekend(date)) {
                    count++;
                }
            }
            attendanceMonthVO.setLeaveDays(count);
        }
        return list;
    }




    /**
     * 查询员工考勤列表
     * 
     * @param oaStaffAttendance 员工考勤
     * @return 员工考勤
     */
    @Override
    public  List<OaStaffAttendance> selectOaStaffAttendanceList(OaStaffAttendance oaStaffAttendance)
    {

        return oaStaffAttendanceMapper.selectOaStaffAttendanceList(oaStaffAttendance);




    }

    @Override
    public List<UserAttendanceDto> selectOaStaffAttendanceList2(OaAttendanceVo oaAttendanceVo) {
        String month = oaAttendanceVo.getMonth();
        String name = oaAttendanceVo.getStaffName();
        // 如果没有指明月份，就默认显示当前月份的考勤数据
//        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like("nick_name",name);

        if (name == null) {
            name = "";
        }
        List<UserAttendanceDto> userAttendanceDtos =  sysUserMapper.listStaffAttendanceVO(name);
        if (month == null) {
            month = DateUtil.format(new java.util.Date(), "yyyyMM");
        }


        String[] monthDayList = DatetimeUtil.getMonthDayList(month);

        List<OaStaffAttendance> oaStaffAttendances =   oaStaffAttendanceMapper.selectOaStaffAttendanceList(null);

        for (UserAttendanceDto userAttendanceDto : userAttendanceDtos) {
            // 获取当前月的日期，格式为yyyyMMdd
            List<HashMap<String, Object>> list = new ArrayList<>();
            for (String day : monthDayList) {
                HashMap<String, Object> map = new HashMap<>();
                OaStaffAttendance oaStaffAttendance2 = this.oaStaffAttendanceMapper.findByStaffId(userAttendanceDto.getUserId(), day);
                // 如果考勤数据不存在，就重新设置数据
                if (oaStaffAttendance2 == null) {
                    Date date = DateUtil.parse(day, "yyyyMMdd").toSqlDate();
                    // 如果是周末就休假
                    if (DateUtil.isWeekend(date)) {
                        map.put("message", OaStaffAttendanceEnum.LEAVE.getMessage());
                        map.put("tagType", OaStaffAttendanceEnum.LEAVE.getTagType());
                    } else {
                        map.put("message", OaStaffAttendanceEnum.NORMAL.getMessage());
                        map.put("tagType", OaStaffAttendanceEnum.NORMAL.getTagType());
                    }
                    map.put("attendanceDate", date);
                } else {
                    map.put("message", oaStaffAttendance2.getStatus().getMessage());
                    map.put("tagType", oaStaffAttendance2.getStatus().getTagType());

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String formattedDate = sdf.format(oaStaffAttendance2.getAttendanceDate());
                    map.put("attendanceDate",formattedDate);
                }
                list.add(map);
            }
            userAttendanceDto.setKqList(list);
        }


        return userAttendanceDtos;

    }

    /**
     * 新增员工考勤
     * 
     * @param oaStaffAttendance 员工考勤
     * @return 结果
     */
    @Override
    public int insertOaStaffAttendance(OaStaffAttendance oaStaffAttendance)
    {
        oaStaffAttendance.setCreateTime(DateUtils.getNowDate());
        return oaStaffAttendanceMapper.insertOaStaffAttendance(oaStaffAttendance);
    }

    /**
     * 修改员工考勤
     * 
     * @param oaStaffAttendance 员工考勤
     * @return 结果
     */
    @Override
    public int updateOaStaffAttendance(OaStaffAttendance oaStaffAttendance)
    {
        oaStaffAttendance.setUpdateTime(DateUtils.getNowDate());
        return oaStaffAttendanceMapper.updateOaStaffAttendance(oaStaffAttendance);
    }

    /**
     * 批量删除员工考勤
     * 
     * @param ids 需要删除的员工考勤主键
     * @return 结果
     */
    @Override
    public int deleteOaStaffAttendanceByIds(Long[] ids)
    {
        return oaStaffAttendanceMapper.deleteOaStaffAttendanceByIds(ids);
    }

    /**
     * 删除员工考勤信息
     * 
     * @param id 员工考勤主键
     * @return 结果
     */
    @Override
    public int deleteOaStaffAttendanceById(Long id)
    {
        return oaStaffAttendanceMapper.deleteOaStaffAttendanceById(id);
    }

    @Override
    public int setAttendance(OaStaffAttendance oaStaffAttendance) {
        QueryWrapper<OaStaffAttendance> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("staff_id", oaStaffAttendance.getStaffId()).eq("attendance_date", oaStaffAttendance.getAttendanceDate());

                OaStaffAttendance oaStaffAttendance1 =oaStaffAttendanceMapper.selectOne(queryWrapper);
                if (oaStaffAttendance1 ==null){
                    return oaStaffAttendanceMapper.insertOaStaffAttendance(oaStaffAttendance);
                }else
                    oaStaffAttendance1.setStatus(oaStaffAttendance.getStatus());
                    return oaStaffAttendanceMapper.updateOaStaffAttendance(oaStaffAttendance1);
    }


}
